<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\Aftermarket as AftermarketModel;
use addons\qingdongams\model\AftermarketType;
use addons\qingdongams\model\Message;
use think\Db;
use think\Log;
/**
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
/**
 * 文章
 */
class Aftermarket extends StaffApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    /**
     * 类型列表
     */
    public function typeList(){
        $pid = input('pid',0);
        $where['pid'] = $pid;
        $model = new AftermarketType();
        $list = collection($model->order('id desc')->where($where)->field('id,name,pid')->select())->toArray();
        $this->success('',$list);
    }

    //添加文章
    public function addArticle()
    {
        $params = $this->request->post();
        if(!$params['title'] || !$params['content']){
            $this->error('请上传文章标题或者内容呢');
        }
        if(!isset($params['img']) || empty($params['img'])){
            $this->error('请上传缩略图');
        }

        $params['content'] = html_entity_decode($params['content']);

        $img = \addons\qingdongams\model\File::where('id',$params['img'])->value('file_path');
        $data = [
            'title' => $params['title'],
            'content' => $params['content'],
            'img'     =>$img,
            'type_ids' => ','.$params['type_ids'].',',
            'product_ids' => $params['product_ids'],
            'method' => $params['method']?? '',
            'desc' => $params['desc']?? '',
            'create_staff_id' => $this->auth->id,
        ];
        $commentModel = new AftermarketModel();
        if($commentModel->allowField(true)->isUpdate(false)->save($data)){
            $this->success('文章添加成功');
        }else{
            $this->error('文章添加失败');
        }
    }

    // 修改文章
    public function editArticle()
    {
        $params = $this->request->post();
        if(!isset($params['id']) || empty($params['id'])){
            $this->error('文章id呢？');
        }
        $commentModel = new AftermarketModel();
        $row  = $commentModel->get($params['id']);
        if(!$row){
            $this->error('暂无此文章');
        }
        if(!isset($params['type_ids']) || empty($params['type_ids'])){
            $this->error('请上传文章类型');
        }
        if(!isset($params['product_ids']) || empty($params['product_ids'])){
            $this->error('请上传产品ID');
        }
        if(!$params['title'] || !$params['content']){
            $this->error('请上传文章标题或者内容呢');
        }
        Log::write('接受前------'.$params['content']);
        $params['content'] = html_entity_decode($params['content']);
        Log::write('接受后------'.$params['content']);
        $data = [
            'type_ids' => ','.$params['type_ids'].',',
            'product_ids' => $params['product_ids'],
            'title' => $params['title'],
            'content' => $params['content'],
            'method' => $params['method']?? '',
            'desc' => $params['desc']?? '',
        ];
        if(isset($params['img']) && !empty($params['img']) && is_numeric($params['img'])){
            $img = \addons\qingdongams\model\File::where('id',$params['img'])->value('file_path');
            $data['img'] = $img;
        }
        if($commentModel->isUpdate(true)->save($data,['id'=>$params['id']])){
            $this->success('文章修改成功');
        }else{
            $this->error('文章修改失败');
        }
    }

    //文章列表
    public function articleList()
    {
        $limit = input("limit/d", 10);
        $params = $this->request->post();
        $where = [];
        $followWhere=[];
        if(isset($params['type_ids']) && $params['type_ids']){
            $type_ids=explode(',',$params['type_ids']);
            if(count($type_ids) > 1){
                foreach ($type_ids as $tid){
                    $tid=intval($tid);
                    $followWhere[] = ['exp', Db::raw('FIND_IN_SET(' .$tid. ',type_ids)')];
                }
            }else{
                $where['type_ids'] = ['like','%,'.$params['type_ids'].',%'];
            }
        }
        if(isset($params['product_ids'])){
            $where['product_ids'] = $params['product_ids'];
        }
        if(isset($params['name'])){
            $where['title'] = ['like','%'.$params['name'].'%'];
        }
        $comments = AftermarketModel::where($where)->with('staff')->field('id,create_staff_id,product_ids,type_ids,title,content,img,desc,method,click_number,comment_num,createtime')->paginate($limit);
        $this->success('请求成功', $comments);
    }

    public function detail(){
        $id = input("id");
        if(!isset($id) || !$id){
            $this->error('参数缺失');
        }

        //标记通知已读
        Message::setRead(Message::ARTICLE_TYPE, $id, $this->auth->id);
        $detail = AftermarketModel::where('id',$id)->with('staff')->field('id,create_staff_id,product_ids,type_ids,title,content,img,desc,method,click_number,comment_num,createtime')->find();

        preg_match_all('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$detail['content'],$match);
        foreach ($match[1] as $v){
            $detail['content']=str_replace($v,cdnurl($v,true),$detail['content']);
        }
        $this->success('请求成功', $detail);
    }
    /**
     * 文章浏览次数
     * @throws \think\Exception
     */
    public function viewArticle(){
        $id = input('id');
        if(!$id){
            $this->error('文章id呢？');
        }
        $articleModel = new AftermarketModel();
        $row = $articleModel->get($id);
        if(!$row){
            $this->error('文章不存在');
        }
        if($articleModel->where(['id'=>$id])->setInc('click_number')){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }

}
